<template>
  <div v-loading="flyLoading" :class="{'mobile-create': showMobilePage}" class="create-sign-up">
    <explanation :explanation="explanationObj" is-expand style="margin: 0;"/>
    <div :class="{'pb55':device!=='mobile'}" class="page-container">
      <!-- 供应商信息 -->
      <CreateSupplierInfo
        ref="supplierInfoRef"
        v-model="supplierInfo"
        :row-span="12"
        :show-mobile-page="showMobilePage"
        :module-type="TAG_MODULES.RESOURCE"
        :is-draft="showDraftBtn"
        @setSupplierId="setSupplierId"
        @setAccountsReceivable="setAccountsReceivable"/>
      <div class="account-header">
        <Title title="收款账户" style="font-size:16px">
          <span class="title-tip">若供应商无收款账户信息，请前往供应商详情进行新增</span>
        </Title>
      </div>
      <paymentInfo
        v-if="flag"
        ref="paymentInfoRef"
        :account-list-data="accountsReceivable.list"
        :account-list="getAccountList"
      />
      <!-- 账号信息 -->
      <AccountInfo
        ref="accountInfoRef"
        v-model="accountsInfoList"
        :show-mobile-page="showMobilePage"
        :form-fly-user="Boolean(flyUserId)"
        style="margin: 32px 0 20px 0;"/>
      <audit-process
        ref="auditProcess"
        :loading="loading"
        v-model="auditInfo"
        :default-aduitor-list="[userInfo]"

        :old-audit-info="oldAuditInfo"
        :flow-structure="processDetail"
        :is-modify="Boolean(remodifyId)"
        :disable="Boolean(remodifyId)"
        :is-modify-form="Number(isModifyForm)"
        :current-process-index="Number(currentProcessIndex)"
        @submit="submit(SUBMITTYPE.SUBMIT,$event)"
        @getProcess="getProcess" />
      <fixed-pagination>
        <div class="center">
          <el-button v-if="showDraftBtn" class="empty-btn-style" size="small" type="info" @click="submit(SUBMITTYPE.DRAFT)">保存草稿</el-button>
          <el-button size="small" type="primary" @click="openDrawer()">发起审批</el-button>
          <el-button class="cancel-btn-style" size="small" @click="toBack">返回</el-button>
        </div>
      </fixed-pagination>
    </div>
  </div>
</template>

<script>
// components
import CreateSupplierInfo from '@/components/SignUp/createSupplierInfo';
import paymentInfo from '@/views/signUp/components/paymentInfo';
import AuditProcess from '@/components/Common/auditProcess';
import AccountInfo from '@/components/SignUp/accountInfo';
import Title from '@/components/Title';
import explanation from '@/components/Common/explanation';
// tool
import { mapState } from 'vuex';
import ElMessage from '@/utils/message';
import { createAuditStructure } from '@/utils/aduitor';
import { SUBMITTYPE } from '@/utils/const/cost';
import { generateUUID, isContained } from '@/utils/tools';
import { TAG_MODULES } from '@/utils/const';
import { companyNormalAccount, personNormalAccount } from '@/views/signUp/components/data';
import { filterToSignUpMapping, supplierMapping } from '@/utils/signUpMappingResource';
import { deepClone } from '@/utils';
import { getFirstDepartment } from '@/utils/index';

// api
import { createSignUp, editSignUp, formSubmit, getPlatformConfig, signUpDetail } from '@/api/signUp';
import { processManagementDetail } from '@/api/legal';
import { upDetail } from '@/api/filter';
import { getResouceInfo } from '@/api/resource';
import flyMixins from '@/mixins/flyUser';
import processCreate from '@/mixins/processCreate';
import mobileCreate from '@/mixins/mobileCreate';

export default {
  components: { CreateSupplierInfo, paymentInfo, AccountInfo, Title, AuditProcess, explanation },
  mixins: [flyMixins, processCreate, mobileCreate],
  data() {
    return {
      id: '',
      TAG_MODULES,
      SUBMITTYPE,
      supplierInfo: { // 供应商信息
        createUser: '',
        departmentId: '',
        supplierType: '',
        channelName: '',
        channelId: '',
        cooperationStatus: '',
        taxpayerIdentificationNumber: '',
        publishedStatus: '',
        sex: '',
        taxRate: '',
        region: '',
        address: '',
        phone: '',
        wxCode: '',
        idCard: [],
        remark: ''
      },
      accountsReceivable: { // 收款账户
        isOpenCloud: true,
        list: []
      },
      accountsInfoList: [], // 账号信息
      auditInfo: {
        activeTime: null,
        isSigner: 0,
        countersignSet: 0,
        process: [],
        senders: [],
        id: null
      }, // 流程信息
      processDetail: null,
      isEdit: false,
      remodifyId: null, // 修改，审批流程不能修改
      reapplyId: null, // 重新申请
      explanationObj: {
        content: '',
        styConfig: ''
      }, // 审批说明
      loading: false,
      flag: true,
      oldAuditInfo: null, // 保存旧流程用于比较，修改的情况需要判断流程是否发生变动
      flyUserId: '',
      flyLoading: false,
      supplierId: ''
    };
  },
  computed: {
    ...mapState({
      'device': state => state.app.device,
      'userInfo': state => state.user.userInfo
    }),
    isCompany() { // 是否是公司类型
      return this.supplierInfo.supplierType === 1;
    },
    processStructure() {
      if (!this.processDetail) return [];
      return this.processDetail.process || [];
    },
    showDraftBtn() {
      return !!((!this.remodifyId && !this.reapplyId) || this.createNew);
    },
    getAccountList() {
      return this.isCompany ? companyNormalAccount : personNormalAccount;
    }
  },
  watch: {
    'supplierInfo.supplierType'() {
      this.flag = false;
      this.$nextTick(() => {
        this.flag = true;
      });
    }
  },
  created() {
    this.createNew = Number(this.$route.query.createNew) || 0;
    this.flyUserId = Number(this.$route.query.flyUserId) || '';
    const id = this.$route.params.id;
    const { remodifyId, reapplyId, mediumId, fromResource } = this.$route.query;
    this.remodifyId = remodifyId;
    this.reapplyId = reapplyId;
    const filterId = this.$route.query.filterId; // 从达人初筛跳转新建
    filterId && this.setMasterAccountData(filterId);
    if (id) {
      this.id = id;
      this.isEdit = true;
      this.getData();
      this.reapplyId && this.getExplanation();
    } else {
      this.isEdit = false;
      this.getExplanation();
      if (this.flyUserId) {
        this.getUserInfo();
        return;
      }
      if (mediumId && fromResource) {
        this.getResourceInfo(mediumId);
        return;
      }
      this.$nextTick(() => {
        this.$refs.accountInfoRef && this.$refs.accountInfoRef.addAccount();
      });
    }
  },
  methods: {
    getData() {
      if (!this.id && this.id !== 0) return;
      signUpDetail(this.id).then(res => {
        if (res.data) {
          const accountsInfoList = res.data.accountsInfoList || [];
          accountsInfoList.forEach(i => {
            if (i.cooperationDepartmentName && i.cooperationDepartmentName.length) {
              i.cooperationDepartment = i.cooperationDepartmentName.map(j => j.id);
            } else {
              i.cooperationDepartment = [];
            }
            i._uuid = generateUUID();
            if (i.accountsInfo.orderPlatformId) {
              this.getDynamic(i.accountsInfo.orderPlatformId, i);
            } else {
              this.$set(i.accountsInfo, 'dynamicKey', []);
              this.$set(i.priceInfo, 'dynamicKey', []);
            }
            if (i.contractInfo && i.contractInfo.signStartDate) {
              i.contractInfo.signDate = [i.contractInfo.signStartDate, i.contractInfo.signEndDate];
            }
            if (!i.additionalKey) {
              i.additionalKey = {
                articlesPrice: {},
                nextMonthReportPrice: {},
                nextMonthNotReportPrice: {}
              };
            } else {
            // 引用账号的additionalKey的相关数据可能为null，补上空对象防止报错
              if (!i.additionalKey.articlesPrice) {
                i.additionalKey.articlesPrice = {};
              }
              if (!i.additionalKey.nextMonthReportPrice) {
                i.additionalKey.nextMonthReportPrice = {};
              }
              if (!i.additionalKey.nextMonthNotReportPrice) {
                i.additionalKey.nextMonthNotReportPrice = {};
              }
            }
          });
          this.accountsReceivable = res.data.accountsReceivable;
          this.accountsInfoList = accountsInfoList;
          if (res.data.auditInfo && !this.reapplyId) {
            this.oldAuditInfo = Object.assign({}, res.data.auditInfo);
            this.auditInfo = JSON.parse(JSON.stringify(res.data.auditInfo));
            this.processDetail = JSON.parse(JSON.stringify(res.data.auditInfo));
          }
          delete res.data.accountsReceivable;
          delete res.data.accountsInfoList;
          delete res.data.auditInfo;
          this.supplierInfo = res.data;
          this.supplierId = res.data.channelId;
          this.$refs['supplierInfoRef'].setSupplierInfo(this.supplierId);
          if (this.createNew) {
            this.initCreator();
            this.initInfo();
          }
          // status 0：草稿中
          if (res.data.isDraft || !this.auditInfo || !this.auditInfo.id || this.reapplyId) {
            this.getExplanation();
          }
          this.version = Number(res.data.version) || 0;// 当前详情版本，version存在mixins
        }
      });
    },
    getResourceInfo(mediumId) {
      getResouceInfo(mediumId).then(res => {
        Object.keys(supplierMapping).forEach(key => {
          let value = _.get(res.data, supplierMapping[key]);
          if (key === 'supplierType' && res.data.channelId) {
            value = value === 0 ? 1 : 0;// 资源供应商类型取反了
          }
          _.set(this.supplierInfo, key, value);
        });
        this.supplierId = res.data.channelId;
        this.$nextTick(() => {
          this.$refs.accountInfoRef && this.$refs.accountInfoRef.addAccount(res.data);
        });
      });
    },
    initInfo() {
      this.supplierInfo.channelSn = '';
      this.accountsReceivable.list.map(el => {
        el.createUserName = '';
        el.departmentId = '';
        el.departmentName = '';
      });
      this.accountsInfoList = [ // 账号信息
        {
          _uuid: generateUUID(),
          contractInfo: {
            agentId: this.userInfo.id,
            agentName: this.userInfo.userName,
            workWxCode: '',
            signDate: [],
            cooperationMode: '',
            cooperationType: '',
            legalCode: null,
            autoRenewal: 1,
            settledScreenshot: []
          }, // 签约信息
          accountsInfo: { // 账号信息
            orderPlatformId: '',
            accountName: '',
            link: '',
            accountCode: '',
            operatingModelId: '',
            microtask: 0,
            fansNum: '',
            tagName: null,
            preference: '',
            reason: '',
            notReportPrice: null,
            dynamicKey: []
          },
          priceInfo: {
            profitSharingRemark: '',
            guaranteeRemark: '',
            profitSharingRatio: '',
            guaranteePrice: '',
            dynamicKey: []
          }, // 分成信息
          additionalKey: {
            nextMonthReportPrice: {},
            nextMonthNotReportPrice: {},
            articlesPrice: {}
          },
          contractList: [] // 合同信息
        }
      ];
    },
    initCreator() {
      const { departmentAry, id, userName } = this.userInfo;
      this.supplierInfo.departmentId = getFirstDepartment(departmentAry);
      this.supplierInfo.creatorId = id;
      this.supplierInfo.createUser = userName;
    },
    getProcess() {
      this.getProcessDetail(true);
      this.isRefresh = true;
    },
    // 回填达人初筛数据至账号信息
    setMasterAccountData(id) {
      upDetail(id).then(res => {
        if (res.code === 200) {
          Object.keys(filterToSignUpMapping).forEach(key => {
            const value = res.data[key];
            /* if (key === 'category') { // 内容类别多选
              value = value ? value.split(',').map(i => Number(i)) : [];
            } */
            _.set(this.accountsInfoList[0], filterToSignUpMapping[key], value);
          });
          if (res.data.additionalKey) {
            _.set(this.accountsInfoList[0], 'additionalKey', res.data.additionalKey);
          }
        }
      });
    },
    // 供应商选中，关联收款账户数据
    setAccountsReceivable(list) {
      this.accountsReceivable.list = Array.isArray(list) ? list : [];
    },
    openDrawer() { // 2.9.7 流程弹窗
      if (!this.accountsInfoList || this.accountsInfoList.length === 0) {
        this.$message.warning('必须存在一个账号');
        return;
      }
      let existSame = false;
      this.accountsInfoList.forEach(i => {
        const findItem = this.accountsInfoList.find(j => i.accountsInfo.platformId === j.accountsInfo.platformId && i.accountsInfo.accountCode === j.accountsInfo.accountCode && i._uuid !== j._uuid);
        findItem && (existSame = true);
      });
      if (existSame) {
        this.$message.error('账号信息存在重复账号');
        return;
      }
      if (!this.supplierId) {
        this.$message.error('请选择供应商');
        return;
      }
      if (!this.$refs['paymentInfoRef'].accountListData.length) {
        this.$message.error('收款账户信息不能为空');
        return;
      }
      const promise = [];
      promise.push(this.$refs.supplierInfoRef.validateForm());
      promise.push(this.$refs.accountInfoRef.validateForm());
      Promise.all(promise).then(res => { // 表单校验通过，则仅提交供应商表单部分，不提交流程信息，用来获取最新流程
        this.getProcessDetail();
        // 重新申请或者新建
      }).catch(_ => {
        ElMessage.warning('请检查信息是否填写完整');
      });
    },
    getExplanation() { // 获取审批说明
      processManagementDetail({ id: 3527, type: 13 }).then(res => {
        // 审批说明
        const data = res.data[0];
        this.explanationObj.content = data.explanation || '';
        this.explanationObj.styConfig = data.styConfig || '';
      }).catch(err => {
        console.log(err);
      });
    },
    // 获取流程详情
    getProcessDetail(isRefresh = false) {
      this.loading = true;
      const data = Object.assign({}, this.supplierInfo);
      data.type = 13;
      data.accountsInfoList = this.accountsInfoList;
      formSubmit(data).then(res => {
        this.loading = false;
        if (res.code === 200) {
          const data = res.data;
          if (this.remodifyId && !isRefresh) {
            this.isProcessChange(data, this.oldAuditInfo) && this.$refs['auditProcess'].setShowRefresh(true);
          } else {
            this.processDetail = data;
            this.auditInfo.activeTime = data.activationTime;
            this.auditInfo.id = data.id;
            // 创建人回填
            this.auditInfo.process = createAuditStructure(data.process, this.userInfo, this.userInfo);
            this.auditInfo.senders = data.senderDiyUserList || [];
          }
          if (this.remodifyId && isRefresh) { // 修改刷新保存刷新后流程用于对比
            this.oldAuditInfo = Object.assign({}, data);
            this.oldAuditInfo.process.forEach(el => {
              this.oldAuditInfo.templateNodeId = el.id;
            });
            this.oldAuditInfo.activeTime = data.activationTime * 1000;
          }
          this.$refs['auditProcess'].openDrawer();
        } else {
          this.$message.error(res.message);
        }
      }).catch(err => {
        this.loading = false;
        console.log(err);
      });
    },
    isProcessChange(nowAuditInfo = {}, oldAuditInfo = {}) {
      if (nowAuditInfo.activationTime !== (oldAuditInfo.activeTime / 1000)) {
        return true;
      }
      const nowProcessIds = nowAuditInfo && nowAuditInfo.process.map(el => el.id) || [];
      const oldProcessIds = oldAuditInfo && oldAuditInfo.process.map(el => el.templateNodeId) || [];
      if (!isContained(nowProcessIds, oldProcessIds)) {
        return true;
      }
      return false;
    },
    submit(submitType = SUBMITTYPE.SUBMIT, senders = []) { // 1草稿 2保存提交 3重新提交
      this.modifySenders = senders;// 存到mixins
      const params = JSON.parse(JSON.stringify(this.supplierInfo));
      params.submitType = submitType;
      params.isEditAudit = false;
      if (this.remodifyId && this.isRefresh) {
        params.isEditAudit = true;// 修改时，流程被编辑或者更新
      }
      params.accountsReceivable = this.accountsReceivable;
      // params.accountsInfoList = this.accountsInfoList;
      // 不能直接赋值accountsInfoList，底下删掉了signDate，若接口返回错误，返回编辑/新建，会将签约日期清空
      params.accountsInfoList = deepClone(this.accountsInfoList);
      params.auditInfo = this.auditInfo;
      if (this.createNew) {
        delete params.id;
      }
      params.accountsInfoList.forEach(item => {
        if (item.contractInfo && item.contractInfo.signDate) {
          item.contractInfo.signStartDate = item.contractInfo.signDate[0];
          item.contractInfo.signEndDate = item.contractInfo.signDate[1];
          delete item.contractInfo.signDate;
        }
      });
      if (!params.accountsInfoList || params.accountsInfoList.length === 0) {
        this.$message.warning('必须存在一个账号');
        return;
      }
      if (this.isModifyForm) { // 节点修改走编辑的逻辑
        this.handleModifyData(params);
        this.edit(params);
        return;
      }
      const msg = submitType === SUBMITTYPE.DRAFT ? '请确认是否保存草稿' : '请确认是否发起审批';
      this.$confirm(msg, '', {
        confirmButtonText: '确定', type: 'warning', showClose: false,
        center: true, iconClass: 'charge-icon', customClass: 'del-message del-message-cancel'
      }).then(() => {
        if (this.reapplyId || !this.isEdit) {
          this.add(params);
        } else {
          this.handleModifyData(params);
          this.edit(params);
        }
      });
      // 重新申请或者新建
    },
    add(params) {
      if (this.reapplyId && !this.createNew) params.submitType = 3;
      createSignUp(params).then(res => {
        if (res.code === 200) {
          ElMessage.success(params.submitType === SUBMITTYPE.DRAFT ? '保存成功' : '发起成功');
          if (res.data.id && res.data.processId) {
            this.$router.push({
              name: 'signUpDetail',
              query: { signUpId: res.data.id, processId: res.data.processId }
            });
          } else {
            this.toBack();
          }
        } else {
          ElMessage.error(res.message);
        }
      }).catch(err => {
        if (err.code === 502) {
          this.$refs['auditProcess'].setShowRefresh(true);
        }
        this.loading = false;
      });
    },
    edit(params) {
      params.id = this.id;
      editSignUp(params).then(res => {
        if (res.code === 200) {
          ElMessage.success(params.submitType === SUBMITTYPE.DRAFT ? '保存成功' : '发起成功');
          if (res.data.processId) {
            this.$router.push({
              name: 'signUpDetail',
              query: { signUpId: params.id, processId: res.data.processId }
            });
          } else {
            this.toBack();
          }
        } else {
          ElMessage.error(res.message);
        }
      }).catch(err => {
        if (err.code === 502) {
          this.$refs['auditProcess'].setShowRefresh(true);
        }
        if (err.code === 505) { // 节点修改跳转详情
          this.nodeModifyJumpDetail({ routeName: 'signUpDetail', params: {}, query: { signUpId: this.id, processId: this.remodifyId }});
        }
        this.loading = false;
      });
    },
    toBack() {
      this.$router.push({
        name: 'signUp'
      });
    },
    // tool
    getRequired(dynamicKey) { // 获取必填字段
      if (!dynamicKey) return {};
      const requiredModel = {};
      dynamicKey.forEach(i => {
        if (i.required) {
          const type = i.inputType === 0 ? '输入' : '选择';
          const validateType = (msg, item) => {
            return (rule, value, callback) => {
              if (item && (item.value || item.value === 0)) {
                callback();
              } else {
                callback(new Error(msg));
              }
            };
          };
          requiredModel[i.name] = [{ required: true, trigger: 'change', validator: validateType(`请${type}${i.name}`, i) }];
        }
      });
      return requiredModel;
    },
    // 获取动态字段
    getDynamic(platformId, item) {
      getPlatformConfig(platformId).then((res) => {
        if (res.data && res.data.length) {
          this.setDynamic(res.data, item);
        }
      });
    },
    // 设置动态字段
    setDynamic(data, item) {
      const res = data[0].item || [];
      const accounts = res.find(i => i.name === '账号信息');
      const price = res.find(i => i.name === '价格信息');

      const accountsInfoDynamic = accounts ? accounts.item || [] : [];
      const priceInfoDynamic = price ? price.item || [] : [];
      const oldAccountDynamic = item.accountsInfo.dynamicKey || [];
      const oldPriceDynamic = item.priceInfo.dynamicKey || [];
      // 回填值
      this.handelDynamic(accountsInfoDynamic, oldAccountDynamic);
      this.handelDynamic(priceInfoDynamic, oldPriceDynamic);
      if (item) {
        this.$set(item.accountsInfo, 'dynamicKey', accountsInfoDynamic);
        this.$set(item.priceInfo, 'dynamicKey', priceInfoDynamic);
        const accountsRequiredModel = this.getRequired(item.accountsInfo.dynamicKey);
        const priceInfoRequiredModel = this.getRequired(item.priceInfo.dynamicKey);
        this.$set(item.accountsInfo, 'requiredModel', accountsRequiredModel);
        this.$set(item.priceInfo, 'requiredModel', priceInfoRequiredModel);
      }
      this.$refs.accountInfoRef.clearValidate();
    },
    handelDynamic(list, oldData) {
      list.forEach(i => {
        const oldItem = oldData.find(j => j.id === i.id);
        if (oldItem) {
          if (i.inputType === 1 && oldItem.inputType === 1) {
            let curOldItem = {};
            if (oldItem.options) {
              curOldItem = oldItem.options.find(j => j.value === oldItem.value);
            }
            const curNewItem = i.options.find(j => j.value === oldItem.value);
            if (curNewItem && curOldItem.label === curNewItem.label) {
              i.value = oldItem.value;
            } else {
              i.value = '';
            }
          } else if ((i.inputType === 1 && oldItem.inputType === 0) || (i.inputType === 0 && oldItem.inputType === 1)) {
            i.value = '';
          } else {
            i.value = oldItem.value;
          }
        }
      });
    },
    setSupplierId(supplierId) {
      this.supplierId = supplierId;
    }
  }
};
</script>

<style lang="scss" scoped>
.create-sign-up {
  margin: 16px;
  background-color: #fff;
  &::v-deep {
    .el-form {
      .indentation-form-item {
        label {
          line-height: 1.2 !important;
        }
      }
    }
  }
}
.page-container {
  padding: 24px;
  &.pb55 {
    padding-bottom: 55px;
  }
}
.account-header{
  display: flex;
  margin: 20px 0 16px;
  .title-tip{
    font-weight: normal;
    color: #999;
    font-size: 12px;
    margin: 0 4px 0 6px;
  }
  &::v-deep {
    .el-radio{
      display: flex;
      align-items: center;
    }
  }
}
.empty-btn-style {
  border-color: #406EFF;
  background: #fff;
  color: #406EFF;
  width: 80px;
  padding: 7px 0;
  text-align: center;
}
::v-deep {
  .el-cascader {
    width: 240px !important;
  }
}
</style>
